package com.apes.scm.rcl.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.rcl.model.RclPlan;
import com.apes.scm.rcl.repository.RclPlanRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

/**
 * @ClassName RclPlanService
 * @Description TODO
 * @Author pengyb
 * @Date 2019/12/10 10:04
 * @Version 1.0
 **/
@Service("rclPlanService")
public class RclPlanService extends DomainService {
    @Autowired
    private RclPlanRepository rclPlanRepository;

    public RclPlan save(SimpleRequest request) {
        RclPlan plan = request.getO(RclPlan.class);

        LocalDate today = LocalDate.now();
        LocalDate validFrom = localDate(plan.getStartDate());
        LocalDate validPeriod = localDate(plan.getEndDate());
        if (null != validFrom && today.isAfter(validFrom)) throw new RuntimeException("开始日期不能在当前日期前");
        if (null != validFrom && null != validPeriod && validFrom.isAfter(validPeriod))
            throw new RuntimeException("结束日期不能在开始日期前");

        return rclPlanRepository.saveAndFlush(plan);

    }

    public String delete(SimpleRequest request) {
        RclPlan plan = request.getO(RclPlan.class);
        rclPlanRepository.delete(plan);
        return "删除成功";
    }

    public static LocalDate localDate(Date date) {
        if (null == date) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

}
